require "erb"
require "rexml/document"

ARGV[0] = "../LectorFicherosCSV/xml/Automotor.xml"
ARGV[1] = "../LectorFicherosCSV/xml/Persona.xml"

Attribute = Struct.new("Attribute", :name, :type, :label)

def readFileXml ( pathFileXml )
  xml = REXML::Document.new(File.open(pathFileXml))
  xml.root.each_element("class"){ | classChild |
    className = classChild.attributes["name"].to_s
    listAttributes = []
    classChild.each_element("attribute"){ | attributeChild |
      attribute = Attribute.new();
      attribute.name = attributeChild.attributes["name"].to_s
      attribute.type = attributeChild.attributes["type"].to_s
      attribute.label = attributeChild.attributes["label"].to_s
      listAttributes.push(attribute)
    }
    parameters = createConstructor(listAttributes).to_s
    erbClase = getTemplate("../LectorFicherosCSV/templates/Class.template",binding)
    createFile("../LectorFicherosCSV/java/",".java",className,erbClase)
    erbLector = getTemplate("../LectorFicherosCSV/templates/ReadCVSJava.template",binding)
    createFile("../LectorFicherosCSV/java/",".java","ReadFile"+className,erbLector)
    erbTest = getTemplate("../LectorFicherosCSV/templates/Test.template",binding)
    createFile("../LectorFicherosCSV/java/",".java","Test"+className,erbTest)
  }
end

def getParameter ( type, value )
  result = ""
  if type == "Character"
    result = value+".charAt(0)"
  else
    result = type+".valueOf(#{value})"
  end
end

def getTypeParameter ( type )
  if type == "Calendar"
    return "String"
  else
    return type
  end
end

def getTemplate (pathTemplate, binding)
  fileTemplate = File.new( pathTemplate )
  fileJava = fileTemplate.read
  erb = ERB.new fileJava
  return erb.result(binding)
end

def createConstructor (listAttributes)
  value = ""
  listAttributes.each{ |element|
    value += " "+getTypeParameter(element.type)+" "+element.name+","
  }
  return value[0,value.length-1].strip
end

def createParameterConstructor (listAttributes)
  value = ""
  for i in 0..listAttributes.size-1
    javaValue = "values[#{i}]"
    parameter = getTypeParameter(listAttributes[i].type)
    value += getParameter(parameter, javaValue)+","
  end
  return value[0,value.length-1].strip
end


def createFile (pathFile,extension,nameFile, erb)
  fileName = pathFile+nameFile+extension
  newFile = File.open(fileName,"w")
  newFile.print erb
  newFile.close
end

if ARGV[0]
  readFileXml(ARGV[0])
else
  "No existe la ruta de archivo"
end

if ARGV[1]
  readFileXml(ARGV[1])
else
  "No existe la ruta de archivo"
end